package com.inossem.allotin.utils.requestUtils;

import android.app.Activity;
import android.app.ProgressDialog;


import com.inossem.allotin.utils.logger.LogWriter;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Retrofit拦截器
 *
 * @author 詹建宇
 * @time on 2018/11/20 11:13
 * @email jianyu.zhan@inossem.com
 */
public class InossemInterceptor implements Interceptor {

    private Activity context;
    private ProgressDialog dialog;
    private final Charset UTF8 = Charset.forName("UTF-8");
    private String android, java, module, function;

    InossemInterceptor(Activity context, String android, String java, String module, String function) {
        this.context = context;
        this.android = android;
        this.java = java;
        this.module = module;
        this.function = function;
        if (null != context && null == dialog) {
            dialog = new ProgressDialog(context);
            dialog.setMessage("正在加载数据...");
        }
    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        //===========================================Request========================================
        Request request = chain.request();
        RequestBody requestBody = request.body();

        if (null != context) {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (null != dialog && null != context && !dialog.isShowing()) dialog.show();
                }
            });
        }

        String bodys = "";
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            bodys = buffer.readString(charset);
        }
        String method = request.method();
        String urls = request.url().toString();
        String headers = request.headers().toString();

        String requestLog = LogWriter.getRequestLogMsg(android, java, module, function,
                urls, method, headers, bodys);
        LogWriter.saveLog(context, "Request", requestLog);

        //==========================================Response========================================
        Response response = chain.proceed(request);
        ResponseBody responseBody = response.body();

        if (null != responseBody) {
            if (null != context) {
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (null != dialog && null != context) {
                            dialog.cancel();
                            dialog = null;
                        }
                    }
                });
            }
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    e.printStackTrace();
                }
            }

            String responseCode = String.valueOf(response.code());
            String message = response.message();
            String url = response.request().url().toString();
            String body = buffer.clone().readString(charset);

            String responseLog = LogWriter.getResponseLogMsg(android, java, module, function,
                    url, responseCode, body);
            LogWriter.saveLog(context, "Request", responseLog);
        }

        return response;
    }

}
